package com.tc.base.exception;
import com.tc.base.entity.APIResult;
import jodd.util.StringPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/** 
 * 全局异常处理器
 */
@ControllerAdvice
public class AdviceExceptionHandler {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	/*
	 * @InitBinder
	 * @ModelAttribute
	 * @ExceptionHandler
	 * ---------------------------------------------------------------------------
	 * @ExceptionHandler
	 * @ResponseBody
	 * public APIResult<Void> exception(Exception exception, WebRequest request) {
	 * 		APIResult<Void> result = new APIResult<>();
	 * 		result.setState(HttpStatus.BAD_REQUEST.value());
	 * 		return result;
	 * }
	 */
	
	/**
	 * 处理全局hibernate validator异常
	 *
	 * @param exception
	 * @return 
	 */
	@ExceptionHandler(ConstraintViolationException.class)
	@ResponseBody
	public APIResult<Void> handleValidatorException(ConstraintViolationException exception) {
		logger.debug("handle validator exception...");
		APIResult<Void> result = new APIResult<>();
		result.setState(HttpStatus.BAD_REQUEST.value());
		Set<ConstraintViolation<?>> violations = exception.getConstraintViolations();
		StringBuilder errBuilder = new StringBuilder();
		for (ConstraintViolation<?> item : violations) {
			String messagetemplate = item.getMessageTemplate();
			String message = item.getMessage();
			logger.debug("message template key is {}, message is {}.", messagetemplate, message);
			errBuilder.append(message).append(StringPool.SEMICOLON);
		}
		result.setCause(errBuilder.toString());
		return result;
	}
	
	/**
	 * 处理全局异常
	 *
	 * @param exception
	 * @return 
	 */
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public APIResult<Void> handleException(Exception exception) {
		logger.debug("handle exception...");
		APIResult<Void> result = new APIResult<>();
		result.setState(HttpStatus.BAD_REQUEST.value());
		result.setCause(exception.getMessage());
		logger.error("global exception:", exception);
		return result;
	}

}
